layui.config({
    base: '../../layui/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
}).use(['jquery', 'formSelects', 'form', 'layer'], function () {
    const form = layui.form
        , layer = layui.layer
        , $ = layui.jquery;
    form.on('submit(save)', function (data) {
        const params = data.field;
        params.projectId = $("#projectId option:selected").val()
        params.namespaceId = $("#namespaceId option:selected").val()
        params.dockerId = $("#dockerId option:selected").val()
        submit($, params);
        return false;

    });

    function submit($, params) {
        // 获取环境配置项并构造 JSON 数组
        var envList = [];
        $('.env-config').each(function () {
            var key = $(this).find('input[name="envKey[]"]').val();
            var value = $(this).find('input[name="envValue[]"]').val();
            if (key) { // 确保 key 和 value 都不为空
                envList.push({ key: key, value: value });
            }
        });
        // 将环境配置项添加到 params 中
        params.envs = JSON.stringify(envList);
        $.ajax({
            url: '/admDockerDeploy',
            data: JSON.stringify(params),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            type: "put",
            success: function (result) {
                if (result.code == 0) {
                    layer.msg(result.desc, {icon: 1, time: 1000}, function () {
                        CloseWin();
                    })
                } else {
                    layer.msg(result.desc, {icon: 2, time: 3000}, function () {
                    })
                }
            }
        })
    }

    //关闭页面
    function CloseWin() {
        parent.location.reload(); // 父页面刷新
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    }

    $(function () {
        getProject("")
        getDocker("")
        getNamespace("")
        getNacos("")
    })
    projectNameInput = function (e) {
        getProject($("#projectName").val())
    }
    let projectData

    function getProject(projectName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProject/getAll?name=" + projectName,//url
            success: function (result) {
                projectData = result
                $("#projectId").html("");
                var html = "";
                $("#projectId").html("<option value=\"\">请选择项目</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.projectName + "</option>";
                    })
                }
                $("#projectId").append(html);
                if (projectName != null && projectName != ''){
                    $.each(result, function (index, item) {
                        if (projectName==item.projectName){
                            $('#projectId option[value=' + item.id + ']').attr('selected', true)
                        }
                    })
                    $(".projectId").find(".layui-form-select").addClass("layui-form-selected")
                }
                const name = $("#projectName").val();
                if (name != null && name != '') {
                    $.each(result, function (index, item) {
                        if (name==item.projectName){
                            $('#projectId option[value=' + item.id + ']').attr('selected', true)
                        }
                    })
                }
                form.render('select');
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(projectId)", function (data) {
        let value = data.value
        let selectObj = projectData.filter(item => {
            return item.id == value
        })
        $("#projectName").val(selectObj[0].projectName);
    })


    dockerNameInput = function (e) {
        const val = $("#dockerName").val();
        getDocker(val)
    }
    let dockerData

    function getDocker(dockerName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admDocker/getAll?name=" + dockerName,//url
            success: function (result) {
                dockerData = result
                $("#dockerId").html("");
                var html = "";
                $("#dockerId").html("<option value=\"\">请选择docker</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.dockerName + "</option>";
                    })
                }
                $("#dockerId").append(html);
                if (dockerName != null && dockerName != '') {
                    $(".dockerId").find(".layui-form-select").addClass("layui-form-selected")
                }
                const name = $("#dockerName").val();
                if (name != null && name != '') {
                    $.each(result, function (index, item) {
                        if (name==item.dockerName){
                            $('#dockerId option[value=' + item.id + ']').attr('selected', true)
                        }
                    })
                }
                form.render('select');
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(dockerId)", function (data) {
        let value = data.value
        let selectObj = dockerData.filter(item => {
            return item.id == value
        })
        $("#dockerName").val(selectObj[0].dockerName);
    })

    namespaceNameInput = function (e) {
        const val = $("#namespaceName").val();
        getNamespace(val)
    }
    let namespaceData

    function getNamespace(namespaceName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNamespace/getAll?name=" + namespaceName,//url
            success: function (result) {
                namespaceData = result
                $("#namespaceId").html("");
                var html = "";
                $("#namespaceId").html("<option value=\"\">请选择命名空间</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.name + "</option>";
                    })
                }
                $("#namespaceId").append(html);
                form.render('select');
                if (namespaceName != null && namespaceName != '') {
                    $(".namespaceId").find(".layui-form-select").addClass("layui-form-selected")
                }
                const name = $("#namespaceName").val();
                if (name != null && name != '') {
                    $.each(result, function (index, item) {
                        if (name==item.name){
                            $('#namespaceId option[value=' + item.id + ']').attr('selected', true)
                        }
                    })
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(namespaceId)", function (data) {
        let value = data.value
        let selectObj = namespaceData.filter(item => {
            return item.id == value
        })
        $("#namespaceName").val(selectObj[0].name);
    })

    nacosNameInput = function(e){
        const val = $("#nacosName").val();
        getNacos(val)
    }
    let nacosData
    function getNacos(nacosName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNacos/getAll?name="+nacosName,//url
            success: function (result) {
                nacosData = result
                $("#nacosId").html("");
                var html = "";
                $("#nacosId").html("<option value=\"\">请选择nacos</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.nacosName + "</option>";
                    })
                }
                $("#nacosId").append(html);
                form.render('select');
                if (nacosName != null && nacosName !=''){
                    $(".nacosId").find(".layui-form-select").addClass("layui-form-selected")
                }

                const name = $("#nacosName").val();
                if (name != null && name != '') {
                    $.each(result, function (index, item) {
                        if (name==item.nacosName){
                            $('#nacosId option[value=' + item.id + ']').attr('selected', true)
                        }
                    })
                }

            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(nacosId)",function(data){
        let value=data.value
        let selectObj=nacosData.filter(item=>{
            return item.id==value
        })
        $("#nacosName").val(selectObj[0].nacosName);
    })
    $("#close").on('click', function () {
        const index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    });

    // 添加新的环境配置项
    $('.env-configs').on('click', '.add-env', function () {
        var $newRow = $(
            '<div class="env-config d-flex align-items-center">' +
            '   <input type="text" name="envKey[]" placeholder="Key" class="layui-input flex-grow-1" style="width: 200px;">' +
            '   <span class="equals-sign mx-2">=</span>' +
            '   <input type="text" name="envValue[]" placeholder="Value" class="layui-input flex-grow-1" style="width: 200px;">' +
            '   <button type="button" class="layui-btn layui-btn-primary add-env"><i class="layui-icon">&#xe654;</i></button>' +
            '   <button type="button" class="layui-btn layui-btn-danger remove-env"><i class="layui-icon">&#xe640;</i></button>' +
            '</div>'
        );
        $(this).closest('.env-config').after($newRow); // 在当前行之后插入新行
    });

// 删除环境配置项
    $('.env-configs').on('click', '.remove-env', function () {
        $(this).closest('.env-config').remove();
    });
});


